package com.javachmapi.springbootthymeleaf.controller;

import com.javachmapi.springbootthymeleaf.dao.CustomerDao;
import com.javachmapi.springbootthymeleaf.entity.Customer;
import com.javachmapi.springbootthymeleaf.table.PageTableHandler;
import com.javachmapi.springbootthymeleaf.table.PageTableHandler.CountHandler;
import com.javachmapi.springbootthymeleaf.table.PageTableHandler.ListHandler;
import com.javachmapi.springbootthymeleaf.table.PageTableRequest;
import com.javachmapi.springbootthymeleaf.table.PageTableResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerDao customerDao;

    /**
     * 查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Customer get(@PathVariable Integer id) {
        return customerDao.getById(id);
    }

    /**
     * 新增
     * @param customer
     * @return
     */
    @PostMapping
    public Customer add(@RequestBody Customer customer) {
         customerDao.save(customer);
        System.out.println("进入新增页面");
         return customer;
    }

    /**
     * 编辑
     * @param customer
     * @return
     */
    @PutMapping
    public Customer update(@RequestBody Customer customer) {
        if(customer.getId()!=null){
            customerDao.update(customer);
        }
        System.out.println(customer.toString());
        System.out.println("进入修改页面");
        return customer;
    }

    /**
     * 得到列表
     * @param request
     * @return
     */
    @GetMapping
    public PageTableResponse list(PageTableRequest request) {
        return new PageTableHandler(new CountHandler() {
            @Override
            public int count(PageTableRequest request) {
                return customerDao.count(request.getParams());
            }
        }, new ListHandler() {

            @Override
            public List<Customer> list(PageTableRequest request) {
                return customerDao.list(request.getParams(), request.getOffset(), request.getLimit());
            }
        }).handle(request);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id) {
        customerDao.delete(id);
    }
}
